/************************************************************************
 * The code is owned by mainframer.cn and Shang Tao
 * Without aproval of mainframer.cn and Shang Tao, removing the copyright
 * infomation is regarded as invassion of proprietary copyright
 ***********************************************************************/
package com.mr.qa.taglib;

//import com.mr.qa.UserSession;
//import com.mr.qa.UserSessionUtil;
//import com.mr.qa.bo.QuestionCategory;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspTagException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.BodyTagSupport;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.Transaction;

import com.mr.qa.bo.SharedFile;
import com.mr.qa.bo.SharedFileCategory;
import com.mr.qa.dao.impl.SharedFileCategoryDAO;
import com.mr.qa.dao.impl.SharedFileDAO;
import com.mr.qa.util.HibernateSessionFactory;


public class SharedFileCategoryTaglib extends BodyTagSupport
{
    private static final Log log = LogFactory.getLog(SharedFileCategoryTaglib.class);
    
    private String resultKind;
    public void setResultKind(String resultKind)
    {
        this.resultKind = resultKind;
    }
    
    public String getResultKind()
    {
        return resultKind;
    }
    
    public int doStartTag() throws JspException
    {
        try
        {
            JspWriter out = pageContext.getOut();
            if("lefttree".equals(this.resultKind))
            {
                out.println(makeLeft());
            }
            else if("dropdown".equals(this.resultKind))
            {
                out.println(makeDropdownList());
            }
            else if("navilinks".equals(this.resultKind))
            {
                HttpServletRequest request = (HttpServletRequest)this.pageContext.getRequest();
                SharedFileCategory sfc = (SharedFileCategory)request.getAttribute("sfc");
                if(sfc == null)
                {
                    SharedFile sf = (SharedFile)request.getAttribute("sharedfile");
                    sfc = sf.getMrIaskSharedFileCategory();
                }
                out.println(makeNaviLinks(sfc,request.getContextPath()));
            }
            else if("top".equals(this.resultKind))
            {
                out.println(this.makeTop());
            }
            else if("rank".equals(this.resultKind))
            {
                this.makeRankList();
            }
        }
        catch (Exception e)
        { 
            //throw new JspException(e);
        }
        return this.EVAL_PAGE;
    }
    public int doEndTag() throws JspTagException 
    {
        return 0;
    }
    
    
    private String makeRankList()
    {
        try
        {
            HttpServletRequest request = (HttpServletRequest)this.pageContext.getRequest();
            SharedFileDAO shareFileDAO = new SharedFileDAO();
            Transaction tx = null;
            List list = null;
            try
            {
                tx = HibernateSessionFactory.getSession().beginTransaction();
                shareFileDAO.setPage(1,10);
                list = shareFileDAO.rankSharedFiles();
                tx.commit();
            }
            catch(Exception e)
            {
                log.error(e);    
            }
            finally
            {
                HibernateSessionFactory.closeSession();
            }
            if(list == null)return "";
            request.setAttribute("sharedfileranklist",list);
            return "";
            /*
            StringBuffer bf = new StringBuffer();
            SharedFile sf = null;
            if(list.size() >0)
            {
                String name = "";
                for(int i=0;i<list.size();i++)
                {
                    sf = (SharedFile)list.get(i);
                    name = sf.getName();
                    bf.append("<tr><td align='center'>"+(i+1)+"&nbsp;</td>");
                    bf.append("<td><a href='");
                    bf.append(request.getContextPath());
                    bf.append("/sf.mrqa?action=view&id=");
                    bf.append(sf.getId());
                    bf.append("'>");
                    bf.append(name);
                    bf.append("</a></td>");
                    bf.append("</tr>\n");
                }
            }
            return bf.toString();
            */
        }
        catch(Exception e)
        {
            log.warn(e);
        }
        return "";
    }
    
    /**
     * make left categories list
     * @return String
     */
    private String makeLeft()
    {
        try
        {
            HttpServletRequest request = (HttpServletRequest)this.pageContext.getRequest();
            SharedFileCategoryDAO categoryDAO = new SharedFileCategoryDAO();
            SharedFileCategory sfc = null;
            Transaction tx = null;
            List list = null;
            try
            {
                tx = HibernateSessionFactory.getSession().beginTransaction();
                list = categoryDAO.findAll();//level 1
                tx.commit();
            }
            catch(Exception e)
            {
                log.error(e);    
            }
            finally
            {
                HibernateSessionFactory.closeSession();
            }
            if(list == null)return "";
            StringBuffer bf = new StringBuffer();
            if(list.size() >0)
            {
                for(int i=0;i<list.size();i++)
                {
                    sfc = (SharedFileCategory)list.get(i);
                    bf.append("<b><a href='");
                    bf.append(request.getContextPath());
                    bf.append("/sf.mrqa?action=list&catId=");
                    bf.append(sfc.getId());
                    bf.append("'>");
                    bf.append(sfc.getName());
                    bf.append("</a></b><br>");
                    Set level1Cats = sfc.getMrIaskSharedFileCategories();//level 2
                    if(level1Cats.size() >0)
                    {
                        Iterator level1Ite = level1Cats.iterator();
                        while(level1Ite.hasNext())
                        {
                            sfc = (SharedFileCategory)level1Ite.next();
                            bf.append("&nbsp;&nbsp;>><a href='");
                            bf.append(request.getContextPath());
                            bf.append("/sf.mrqa?action=list&catId=");
                            bf.append(sfc.getId());
                            bf.append("'>");
                            bf.append(sfc.getName());
                            bf.append("</a>");
                        }
                    }
                    bf.append("<hr>");
                }
            }
            return bf.toString();
        }
        catch(Exception e)
        {
            log.warn(e);
        }
        return "";
    }

    private String makeDropdownList()
    {
        try
        {
            SharedFileCategoryDAO categoryDAO = new SharedFileCategoryDAO();
            SharedFileCategory sfc = null;
            List list = categoryDAO.findAll();//level 1
            StringBuffer sb = new StringBuffer();
            if(list.size() >0)//level 1
            {
                int level = 1;
                for(int i=0;i<list.size();i++)
                {
                    sfc = (SharedFileCategory)list.get(i);
                    sb.append("<cat level=\"");
                    sb.append(level);
                    sb.append("\" id=\"");
                    sb.append(sfc.getId());
                    sb.append("\" name=\"");
                    sb.append(sfc.getName());
                    if(sfc.getMrIaskSharedFileCategories().size() > 0)
                    {
                        sb.append("\">\n");                    
                        makeNextLevel(sb,level+1,sfc);
                    }
                    else
                    {
                        sb.append("\">");
                    }
                    sb.append("</cat>\n");
                }
            }
            return sb.toString();
        }
        catch(Exception e)
        {
            log.warn(e);
        }
        return "";
    }    
    
    private void makeNextLevel(StringBuffer sb, int level,SharedFileCategory parent)
    {
        Set children = parent.getMrIaskSharedFileCategories();
        if(children.size() >0)
        {
            String indentStr = makeIndentStr(level);
            SharedFileCategory sfc = null;
            Iterator ite = children.iterator();
            while(ite.hasNext())
            {
                sfc = (SharedFileCategory)ite.next();
                sb.append(indentStr);
                sb.append("<cat level=\"");
                sb.append(level);
                sb.append("\" id=\"");
                sb.append(sfc.getId());
                sb.append("\" name=\"");
                sb.append(sfc.getName());
                if(sfc.getMrIaskSharedFileCategories().size() > 0)
                {
                    sb.append("\">\n");                    
                    makeNextLevel(sb,level+1,sfc);
                }
                else
                {
                    sb.append("\">");
                }
                if(sfc.getMrIaskSharedFileCategories().size() > 0)
                {
                    sb.append(indentStr);
                }    
                sb.append("</cat>\n");
                
            }
        }
    }    
    
    private String makeNaviLinks(SharedFileCategory sfc,String contextPath)
    {
        if(sfc == null)return "";
        StringBuffer sb = new StringBuffer();
        StringBuffer sb3 = new StringBuffer();
        StringBuffer sb2 = new StringBuffer();
        StringBuffer sb1 = new StringBuffer();
        String action = contextPath+"/sf.mrqa?action=list&catId=";
        if(sfc != null)
        {
            sb3.append("&nbsp;>&nbsp;");
            sb3.append("<a href='");
            sb3.append(action);
            sb3.append(sfc.getId());
            sb3.append("'>");
            sb3.append(sfc.getName());
            sb3.append("</a>");
            SharedFileCategory sfc2 = sfc.getMrIaskSharedFileCategory();
            if(sfc2 != null)
            {
                sb2.append("&nbsp;>>&nbsp;");
                sb2.append("<a href='");
                sb2.append(action);
                sb2.append(sfc2.getId());
                sb2.append("'>");
                sb2.append(sfc2.getName());
                sb2.append("</a>");
                SharedFileCategory sfc1 = sfc2.getMrIaskSharedFileCategory();
                if(sfc1 != null)
                {
                    sb1.append("&nbsp;>>&nbsp;");
                    sb1.append("<a href='");
                    sb1.append(action);
                    sb1.append(sfc1.getId());
                    sb1.append("'>");
                    sb1.append(sfc1.getName());
                    sb1.append("</a>");
                }    
            }
        }
        if(sb1.toString().length() > 0)
            sb.append(sb1);
        if(sb2.toString().length() > 0)
            sb.append(sb2);
        if(sb3.toString().length() > 0)
            sb.append(sb3);
        return sb.toString();
    }    
    
    private String makeTop()
    {
        try
        {
            HttpServletRequest request = (HttpServletRequest)this.pageContext.getRequest();
            String catId = request.getParameter("catId");
            Transaction tx = null;
            try
            {
                tx = HibernateSessionFactory.getSession().beginTransaction();
                SharedFileCategoryDAO categoryDAO = new SharedFileCategoryDAO();
                Collection categories = null;
                if(catId == null)
                {
                    categories = categoryDAO.findAll();
                }
                else
                {
                    SharedFileCategory parent = null;                
                    parent = categoryDAO.findById(new Integer(catId));
                    categories = parent.getMrIaskSharedFileCategories();
                }
                tx.commit();
                //System.out.println("categories="+categories.size());
                String topLinks = makeTopLinks(categories);
                //System.out.println("topLinks="+topLinks);
                if(categories != null)return topLinks;
            }
            catch(Exception e)
            {
                log.error(e);    
            }
            finally
            {
                HibernateSessionFactory.closeSession();
            }
        }
        catch(Exception e)
        {
            log.warn(e);
        }
        return "";
    }
    /**
     * invoked by the above method makeTop
     * @param categories
     * @return
     */
    private String makeTopLinks(Collection<SharedFileCategory> categories)
    {
        StringBuffer bf = new StringBuffer();
        HttpServletRequest request = (HttpServletRequest)this.pageContext.getRequest();
        if(categories.size() > 0)
        {
            Iterator levelIte = categories.iterator();
            SharedFileCategory sfc = null;
            while(levelIte.hasNext())
            {
                sfc = (SharedFileCategory)levelIte.next();
                bf.append("<li><a href='");
                bf.append(request.getContextPath());
                bf.append("/sf.mrqa?action=list&catId=");
                bf.append(sfc.getId());
                bf.append("'>");
                bf.append(sfc.getName());
                bf.append("(");
                bf.append(sfc.getFileCount());
                bf.append(")");
                bf.append("</a>");
            }
        }
        if(bf.toString().length() >0)
            return "<ul id=\"questioncategoryontop\">"+bf.toString()+"</ul>";
        else return "";
        
    }
    
    
    
    private String makeIndentStr(int level)
    {
        String indentStr = "";
        for(int i=0;i<level;i++)indentStr = indentStr+"   ";
        return indentStr;
    }
    
}
